/**
 * Created by vincent on 2017/9/28.
 */
moduleQuiz.controller('QuizTopicQuery', function (LanguageService, $scope, $state, $stateParams, $log, $timeout, EnumService, ConstantService, GaugeResource, $rootScope, DialogService, LoadingService, GaugeTopicGroupResource) {
    initPage($scope);
    $scope.$on("$viewContentLoaded", function () {
        pageOnLoad();
        ConstantService.addState($state.current, true, LanguageService.language('测试题题目管理'));
        $scope.quizTemplateId = $stateParams.quizTemplateId;
        $scope.loadQuizTopic();

        $scope.gaugeTopicTypeOptions = Enums.GaugeTopicTypeEnum.options;
        $scope.gaugeTopicGroupTypeOptions = Enums.GaugeTopicGroupTypeEnum.options;
    });


    $scope.loadQuizTopic = function (successFn) {
        //LoadingService.show();
        GaugeTopicGroupResource.findByGaugeTemplateId({gaugeTemplateId: $scope.quizTemplateId}, function (gaugeTopicGroupResult) {
            $log.debug("当前量表题目组", gaugeTopicGroupResult);
            $scope.currentGaugeTopicGroup = gaugeTopicGroupResult;
            //LoadingService.hide();
            successFn && successFn();
        });
    };

    $scope.addTopic = function () {
        DialogService.open("addQuizTopic", $scope, function(){
            $scope.loadQuizTopic();
        });
    };

    var copyTopic = function (topic) {
        var result = {};
        result.itemCode = topic.itemCode;
        result.type = topic.type;
        result.content = topic.content;
        result.attributes = [];
        angular.forEach(topic.attributes, function (attribute) {
            var attrTemp = {};
            attrTemp.sort = attribute.sort;
            attrTemp.score = attribute.score;
            attrTemp.content = attribute.content;
            result.attributes.push(attrTemp);
        });
        return result;
    };

    //按本题新增题目
    $scope.addTopicTemp = function (gaugeTopic) {
        var newTopic = copyTopic(gaugeTopic);
        $scope.currentGaugeTopicGroup.gaugeTopics.push(newTopic);
    };

    $scope.editTopic = function (topic) {
        $scope.currentTopic = topic;
        $scope.editingTopic = angular.copy($scope.currentTopic);
        $scope.editingTopic.typeOption = EnumService.getEnumObject($scope.editingTopic.type, "GaugeTopicTypeEnum");
        DialogService.open("editQuizTopic", $scope);
    };

    $scope.deleteTopic = function (topic) {
        Alert.confirm(function () {
            for (var i = 0; i < $scope.currentGaugeTopicGroup.gaugeTopics.length; i++) {
                if (topic == $scope.currentGaugeTopicGroup.gaugeTopics[i]) {
                    $scope.currentGaugeTopicGroup.gaugeTopics.remove(i);
                }
            }
            $scope.$apply();
        });
    };

    $scope.addAttribute = function (topic) {
        $scope.currentTopic = topic;
        DialogService.open("addQuizAttribute", $scope);
    };

    $scope.updateConfig = function () {
        //updateConfigGaugeTopicGroup
        DialogService.open("updateConfigGaugeTopicGroup", $scope);
    }

    $scope.editAttribute = function (attribute) {
        $scope.currentAttribute = attribute;
        $scope.editingAttribute = angular.copy($scope.currentAttribute);
        DialogService.open("editQuizAttribute", $scope);
    };

    $scope.deleteAttribute = function (topic, attribute) {
        Alert.confirm(function () {
            for (var i = 0; i < topic.attributes.length; i++) {
                if (attribute == topic.attributes[i]) {
                    topic.attributes.remove(i);
                }
            }
            $scope.$apply();
            $timeout(function () {
                Alert.success();
            }, 300);
        });
    };

    $scope.save = function () {
        //LoadingService.show();
        GaugeTopicGroupResource.save($scope.currentGaugeTopicGroup, function (currentGaugeTopicGroupResult) {
            $log.debug("量表题目保存结果", currentGaugeTopicGroupResult);
            $scope.currentGaugeTopicGroup = currentGaugeTopicGroupResult;
            //LoadingService.hide();
            Alert.success();
        })
    };

    $scope.refresh = function () {
        $scope.queryPara = {};
        $scope.$broadcast("init-select");
    };

    $scope.read = function (workbook) {
        /* DO SOMETHING WITH workbook HERE */
        $log.debug(workbook);
        var rawJson = XLS.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
        $log.debug("excel数据", rawJson);
        if (!checkJson(rawJson)) {
            Alert.error(LanguageService.langauge('数据格式错误!'));
        } else {
            var topicList = jsonToGaugeTopic(rawJson);
            $log.debug("转换后数据", topicList);
            $scope.currentGaugeTopicGroup.gaugeTopics = topicList;
            $scope.$apply();
        }
    };

    function checkWBJson(rawJson) {
        var first = rawJson[0];
        /** @namespace first.Answer */
        /** @namespace first.Title */
        return (first && first.Title && first.Type && first.A && first.B && first.Answer);
    }

    function addAttribute(answer, itemCode, sort, content, currentTopic) {
        if (StringUtils.isNlOrUndOrEmpty(content)) {
            return;
        }
        var currentAttribute = {};
        currentAttribute.sort = sort;
        currentAttribute.score = answer.includes(itemCode) ? 1 : 0;
        currentAttribute.content = content;
        currentTopic.attributes.push(currentAttribute);
    }

    function jsonToGaugeTopicWB(rawJson) {
        var topicList = [];
        rawJson.forEach(function (rawGaugeTopic, index) {
            var currentTopic = {};
            currentTopic.itemCode = index;
            if (parseInt(rawGaugeTopic['Type']) === 0) {
                currentTopic.type = 'SELECT'
            } else {
                currentTopic.type = 'CHECKBOX_BOOLEAN';
            }
            currentTopic.content = rawGaugeTopic['Title'];
            currentTopic.attributes = [];
            addAttribute(rawGaugeTopic.Answer, 'A', 1, rawGaugeTopic.A, currentTopic);
            addAttribute(rawGaugeTopic.Answer, 'B', 2, rawGaugeTopic.B, currentTopic);
            addAttribute(rawGaugeTopic.Answer, 'C', 3, rawGaugeTopic.C, currentTopic);
            addAttribute(rawGaugeTopic.Answer, 'D', 4, rawGaugeTopic.D, currentTopic);
            addAttribute(rawGaugeTopic.Answer, 'E', 5, rawGaugeTopic.E, currentTopic);
            addAttribute(rawGaugeTopic.Answer, 'F', 6, rawGaugeTopic.F, currentTopic);
            topicList.push(currentTopic);
        });
        return topicList;
    }

    /**
     * "[{
     *      "Title":"“倒拿或乱用工具会导致事故”，这种说法正确吗？",
     *      "Type":"0",
     *      "question_knowledge":"正确",
     *      "level":"0",
     *      "Pk":"1",
     *      "Map":"1",
     *      "A":"正确",
     *      "B":"错误",
     *      "Answer":"A"
     *  },{
     *      "Title":"文中，梯子、梯凳有几条安全须知？",
     *      "Type":"0",
     *      "question_knowledge":"9条",
     *      "level":"0",
     *      "Pk":"1",
     *      "Map":
     *      "1",
     *      "A":"9条",
     *      "B":"6条",
     *      "C":"7条",
     *      "D":"8条",
     *      "Answer":"A"
     *  }]"
     * @param workbook
     */
    $scope.readWB = function (workbook) {
        /* DO SOMETHING WITH workbook HERE */
        $log.debug(workbook);
        var rawJson = XLS.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
        $log.debug("excel数据", rawJson);
        if (!checkWBJson(rawJson)) {
            Alert.error(LanguageService.language('数据格式错误!'));
        } else {
            var topicList = jsonToGaugeTopicWB(rawJson);
            $log.debug("转换后数据", topicList);
            $scope.currentGaugeTopicGroup.gaugeTopics = topicList;
            $scope.$apply();
        }
    };


    var checkJson = function (jsonData) {
        if (jsonData.length <= 0) {
            return false;
        }
        if (jsonData[0]["GaugeTopic_itemCode"] == undefined
            || jsonData[0]["GaugeTopic_type"] == undefined
            || jsonData[0]["GaugeTopic_content"] == undefined) {
            return false;
        }
        for (var i = 0; i < jsonData.length; i++) {
            if (jsonData[i]["GaugeTopic_itemCode"] == undefined
                && jsonData[i]["GaugeTopicAttribute_sort"] == undefined) {
                return false;
            }
            if (jsonData[i]["GaugeTopic_itemCode"] != undefined
                && (jsonData[i]['GaugeTopic_type'] == undefined
                    || jsonData[i]['GaugeTopic_content'] == undefined)) {
                return false;
            }
            if (jsonData[i]["GaugeTopicAttribute_sort"] != undefined
                && (jsonData[i]['GaugeTopicAttribute_score'] == undefined
                    || jsonData[i]['GaugeTopicAttribute_content'] == undefined)) {
                return false;
            }
        }
        return true;
    };

    var jsonToGaugeTopic = function (jsonData) {
        var topicList = [];
        var currentTopic = {
            attributes: []
        };
        var currentAttribute = {};
        for (var i = 0; i < jsonData.length; i++) {
            if (jsonData[i]['GaugeTopic_itemCode'] != undefined) {
                if (currentTopic.itemCode != undefined) {
                    topicList.push(angular.copy(currentTopic));
                }
                currentTopic = {
                    attributes: []
                };
                currentAttribute = {};
                currentTopic.itemCode = parseInt(jsonData[i]['GaugeTopic_itemCode']);
                currentTopic.type = jsonData[i]['GaugeTopic_type'];
                currentTopic.content = jsonData[i]['GaugeTopic_content'];
                currentAttribute.sort = jsonData[i]['GaugeTopicAttribute_sort'];
                currentAttribute.score = jsonData[i]['GaugeTopicAttribute_score'];
                currentAttribute.content = jsonData[i]['GaugeTopicAttribute_content'];
                currentAttribute.nextItemCode = jsonData[i]['GaugeTopicAttribute_nextItemCode'];
                currentTopic.attributes.push(angular.copy(currentAttribute));
            } else {
                currentAttribute = {};
                currentAttribute.sort = jsonData[i]['GaugeTopicAttribute_sort'];
                currentAttribute.score = jsonData[i]['GaugeTopicAttribute_score'];
                currentAttribute.content = jsonData[i]['GaugeTopicAttribute_content'];
                currentAttribute.nextItemCode = jsonData[i]['GaugeTopicAttribute_nextItemCode'];
                currentTopic.attributes.push(angular.copy(currentAttribute));
            }
        }
        if (currentTopic.itemCode != undefined) {
            topicList.push(angular.copy(currentTopic));
        }
        return topicList;
    };

    $scope.error = function (e) {
        /* DO SOMETHING WHEN ERROR IS THROWN */
        $log.debug(e);
    };

});